package com.malex.mxtracker.servlet;

import com.malex.mxtracker.action.ActionHandler;
import com.malex.mxtracker.action.ActionResult;
import com.malex.mxtracker.exception.WrongCommandException;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Logger;


/**
 * @author Manusovich Alexander
 */
@SuppressWarnings("serial")
public class ExecuteMailHandlerServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(ActionHandler.class.getName());

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        try {
            MimeMessage message = new MimeMessage(session, req.getInputStream());
            String from = "mail";
            Address[] fromAddresses = message.getFrom();
            if (fromAddresses != null && fromAddresses.length > 0) {
                from = fromAddresses[0].toString();
            }
            String request;
            Object content = message.getContent();
            if (content instanceof String) {
                request = (String) content;
            } else {
                Multipart multipart = (Multipart) content;
                request = (String) multipart.getBodyPart(0).getContent();
            }
            log.info("mail from " + from + " request " + request);
            try {
                ActionResult result = new ActionHandler(request, from).execute();
                StringBuffer sb = new StringBuffer();
                if (result != null && result.getReport() != null) {
                    for (String s : result.getReport()) {
                        sb.append(s).append("\n");
                    }
                    answer(message, request, sb.toString());
                }
            } catch (WrongCommandException e) {
                e.printStackTrace();
                answer(message, request, e.getMessage());
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    private void answer(final MimeMessage message,
                        final String request,
                        final String sb) throws MessagingException, UnsupportedEncodingException {
        Properties properties = new Properties();
        Session mailsession = Session.getDefaultInstance(properties, null);
        Message msg = new MimeMessage(mailsession);
        msg.setFrom(new InternetAddress("manusovich.mobile@gmail.com", "mxTracker"));
        for (Address to : message.getFrom()) {
            msg.addRecipient(Message.RecipientType.TO, to);
        }
        msg.setSubject("mxTracker Response for <" + request + ">");
        msg.setText(sb);
        if (message.getFrom() != null && message.getFrom().length > 0) {
            log.info("send mail to " + message.getFrom()[0] + " body: " + sb);
        }
        Transport.send(msg);
    }

}